<?php

namespace app\admin\controller\auth;

use app\admin\controller\Backend;
use fast\Random;
use fast\Tree;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    protected $model = null;
    //当前登录管理员所有子节点组别
    protected $childrenIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('admin/admin', 'service');

        $groups = $this->auth->getGroups();

        // 取出所有分组
        $grouplist = model('admin/auth_group')->all(['status' => 'normal']);
        $objlist = [];
        foreach ($groups as $K => $v)
        {
            // 取出包含自己的所有子节点
            $childrenlist = Tree::instance()->init($grouplist)->getChildren($v['id'], TRUE);
            $obj = Tree::instance()->init($childrenlist)->getTreeArray($v['pid']);
            $objlist = array_merge($objlist, Tree::instance()->getTreeList($obj));
        }
        $groupdata = [];
        foreach ($objlist as $k => $v)
        {
            $groupdata[$v['id']] = $v['name'];
        }
        $this->childrenIds = array_keys($groupdata);
        $this->view->assign('groupdata', $groupdata);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $groupData = model('admin/auth_group')->where('status', 'normal')->column('id,name');

            $childrenAdminIds = [];
            $authGroupList = model('AuthGroupAccess')
                    ->field('uid,group_id')
                    ->where('group_id', 'in', $this->childrenIds)
                    ->select();
            
            $adminGroupName = [];
            foreach ($authGroupList as $k => $v)
            {
                $childrenAdminIds[] = $v['uid'];
                if (isset($groupData[$v['group_id']]))
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupData[$v['group_id']];
            }     
            
            list($where, $sort, $order, $offset, $limit, $field, $extra) = $this->buildparams();
            $where['id'] = ['in', $childrenAdminIds];
            $extra = ['group_access'];
            $result = $this->model->lists($where,$limit, $offset, $sort.' '.$order, $field, $extra);


            $result->each(function($item, $key) use ($adminGroupName){
                $groups = isset($adminGroupName[$item->id]) ? $adminGroupName[$item->id] : [];

                $item->groups_ids = \fast\ArrayHelper::get_ids_arr(collection($item->group_access)->toArray(), 'group_id');
                $item->groups_text = implode(',', array_values($groups));
                return $item;

            });
            return $this->success('Operation completed', null, $result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                
                $this->model->startTrans();
                $row = $this->model->add($params);
                if($row === false) {
                    $this->model->rollback();
                    return $this->error($this->model->getError());
                } 
                $group = $this->request->post("group/a");
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenIds, $group);
                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $row->getAttr('id'), 'group_id' => $value];
                }
                $ret = model('admin/auth_group_access')->saveAll($dataset);
                if($ret === false) {
                    $this->model->rollback();
                    return $this->error(model('admin/auth_group_access')->getError());
                }
                $this->model->commit();
            }

            return $this->success(lang('Operation completed'));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) $this->error(__('No Results were found'));
        
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($params['password'])
                {
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                }
                else
                {
                    unset($params['password'], $params['salt']);
                }
                $this->model->startTrans();
                $row = $this->model->save($params, ['id' => $ids], 'edit');
                if($row === false) {
                    $this->model->rollback();
                    return $this->error($this->model->getError());
                }

                // 先移除所有权限
                model('admin/auth_group_access')->where('uid', $row->getAttr('id'))->delete();
                $group = $this->request->post("group/a");
                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenIds, $group);
                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $row->getAttr('id'), 'group_id' => $value];
                }
                $ret = model('admin/auth_group_access')->saveAll($dataset);
                if($ret === false) {
                    $this->model->rollback();
                    return $this->error(model('admin/auth_group_access')->getError());
                }
                $this->model->commit();
            }
            return $this->success(lang('Operation completed'));
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v)
        {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenIds;
            $groups = $this->auth->getGroups();
            if ($groups[0]['uid'] == $ids)
            {
                return $this->error(__('You can not delete yourself'));
            }
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function($query) use($childrenGroupIds) {
                        $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
                    })->select();
            if ($adminList)
            {
                $deleteIds = [];
                foreach ($adminList as $k => $v)
                {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->id]);
                if ($deleteIds)
                {
                    $this->model->destroy($deleteIds);
                    model('admin/auth_group_access')->where('uid', 'in', $deleteIds)->delete();
                }
            }
            return $this->success(lang('Operation completed'));
        }
        return;
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->code = -1;
    }

}
